#!/bin/bash
#Author:        rengyi yan
#Date Time:     2015-08-03 10:40:41
#Descriptions:  auto install jdk

echo "*****************install java sdk********************************"

RETVAL=0
JAVA_VERSION=0

#Step 1:  checking java installed by centos system
yum list installed | grep java > /dev/null 2>&1
RETVAL=$?

#Step 2: if java is already installed then uninstall it
#	 else install the jdk you wanted
if [ $RETVAL = 0 ];then
   yum -y remove java*
   yum -y remove tzdata-java*
   sed -i '/export JAVA_HOME=\/etc\/alternatives\/java_sdk_openjdk/d' /etc/profile
   sed -i '/export CLASSPATH=.:$JAVA_HOME\/jre\/lib\/rt.jar:$JAVA_HOME\/lib\/dt.jar:$JAVA_HOME\/lib\/tools.jar/d' /etc/profile
   sed -i '/export PATH=$PATH:$JAVA_HOME\/bin/d' /etc/profile
   read -p "Please input the java version you want to install like this: x.y.z    " JAVA_VERSION
   yum -y install java-${JAVA_VERSION}-openjdk*
else
   read  -p "Please input the java version you want to install like this: x.y.z   " JAVA_VERSION
   yum -y install java-${JAVA_VERSION}-openjdk*
fi 

#Step 3: setting JAVA_HOME & CLASSPATH envrioment variables
sed -i '$a\\n' /etc/profile
sed -i '$a\export JAVA_HOME=/etc/alternatives/java_sdk_openjdk'  /etc/profile
sed -i '$a\export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar'  /etc/profile
sed -i '$a\export PATH=$PATH:$JAVA_HOME/bin'  /etc/profile
sed -i '$a\export JRE_HOME=$JAVA_HOME/jre' /etc/profile

. /etc/profile

echo "***************congratulations,jdk install complete*****************"
java -version
echo "********************************************************************"
